
package com.william.killian.trivia.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name="Question")
public class Question implements Serializable
{
    private static final long serialVersionUID = -879916484807070727L;

    @Element(name="Title")
    private String text;
    
    @ElementList(inline=true)
    private List <Answer> answer;

    private int correctAnswerCount;
    
    public Question () {
        text = "New Question";
        answer = new ArrayList <Answer> ();
        correctAnswerCount = -1;
    }
    
    public List <Answer> getAnswers ()
    {
        return answer;
    }

    public String getText ()
    {
        return text;
    }
    
    public boolean hasMultipleAnswers ()
    {
        if (correctAnswerCount < 0)
        {
            correctAnswerCount = 0;
            for (Answer a : answer)
            {
                if (a.isCorrect ())
                {
                    ++correctAnswerCount;
                }
            }
        }
        return (correctAnswerCount > 1);
    }
    
    public String toString ()
    {
        return text;
    }
    
    public String getAnswerText ()
    {
        StringBuilder sb = new StringBuilder ();
        if (hasMultipleAnswers ())
        {
            sb.append ("The correct answers are:\n");
        }
        else
        {
            sb.append ("The correct answer is:\n");
        }
        for (Answer a : answer)
        {
            if (a.isCorrect ())
            {
                sb.append (a.getText ());
                sb.append ("\n");
            }
        }
        return sb.toString ();
    }

    public void deleteAnswer (int i)
    {
        answer.remove (i);
    }

    public void setText (String string)
    {
        text = string;
    }

    public void setAnswers (List <Answer> mList)
    {
        answer.clear ();
        for (Answer a : mList)
            answer.add (a);
    }
}
